
package com.joysuch.wwyt.core.security;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import cn.zlg.common.springmvc.validate.DefaultJsonExceptionResponseBodyBuilder;
import cn.zlg.common.springmvc.validate.JsonExceptionResponseBodyBuilder;
import com.google.gson.Gson;
import com.joysuch.wwyt.core.constant.Constants;
import com.joysuch.wwyt.core.enums.SystemStatusCodes;
import org.apache.shiro.web.filter.authc.UserFilter;
import org.springframework.beans.factory.BeanFactory;

public class UserLoginFilter extends UserFilter {
    private String backUrl = "/";
    private String backLoginUrl = Constants.BACK_LOGIN_URL;
    private BeanFactory beanFactory;

    public UserLoginFilter(BeanFactory beanFactory) {
        this.beanFactory = beanFactory;
    }

    @Override
    protected void redirectToLogin(ServletRequest req, ServletResponse resp) throws IOException {
        JsonExceptionResponseBodyBuilder builder = getJsonBuilder();
        Map<String, Object> build = builder.build(null, null, SystemStatusCodes.SESSION_TIME_OUT.getCode(),
                SystemStatusCodes.SESSION_TIME_OUT.getMessage());
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        resp.getWriter().write(new Gson().toJson(build));
        // if (HttpUtils.isAjaxRequest((HttpServletRequest) req)) {
        // } else {
        // HttpServletRequest request = (HttpServletRequest) req;
        // HttpServletResponse response = (HttpServletResponse) resp;
        // String loginUrl;
        // if (request.getRequestURI().startsWith(request.getContextPath() + getBackUrl())) {
        // loginUrl = getBackLoginUrl();
        // } else {
        // loginUrl = getLoginUrl();
        // }
        // WebUtils.issueRedirect(request, response, loginUrl);
        // }
    }

    private JsonExceptionResponseBodyBuilder getJsonBuilder() {
        JsonExceptionResponseBodyBuilder bean = beanFactory.getBean(JsonExceptionResponseBodyBuilder.class);
        if (bean == null) {
            bean = new DefaultJsonExceptionResponseBodyBuilder();
        }
        return bean;
    }

    public String getBackUrl() {
        return backUrl;
    }

    public void setBackUrl(String backUrl) {
        this.backUrl = backUrl;
    }

    public String getBackLoginUrl() {
        return backLoginUrl;
    }

    public void setBackLoginUrl(String backLoginUrl) {
        this.backLoginUrl = backLoginUrl;
    }

}
